//
// Created by admin on 2022/2/25.
//

#include "thread_pool_cpp.h"

ThreadPool::SimplePool::SimplePool(unsigned int count) {
    addThread(count);
}

ThreadPool::SimplePool::~SimplePool() {
    shut();
//    std::cout << "thread pool shut" << std::endl;
    {
        std::lock_guard<std::mutex> lockGuard(_lock);
        _isRun = false;
    }
//    std::cout << "thread pool state changed" << std::endl;
    _taskCond.notify_all();
//    std::cout << "thread pool call for join" << std::endl;
    for (auto &thread: _pool) {
        if (thread.joinable()) {
//            std::cout << "线程ID" << thread.get_id() << "已经结素" << std::endl;
            thread.join();
        }
    }
//    std::cout << "thread pool close successful" << std::endl;

}

void ThreadPool::SimplePool::addThread(unsigned int num) {
    for (; _pool.size() < DEFAULT_MAX_POOL_NUM && num > 0; --num) {
        /*尝试添加线程*/
        _pool.emplace_back([this]() {
            while (_isRun) {
                Task task;
                {
                    std::unique_lock<std::mutex> uniqueLock{_lock};
                    _taskCond.wait(uniqueLock, [this]() {
                        return !_isRun || !_tasks.empty();
                    });
                    /*任务全部结束*/
                    if (!_isRun && _tasks.empty()) {
                        return;
                    }
                    task = std::move(_tasks.front());
                    _tasks.pop();
                }
                _freeCount--;
                task();
                _freeCount++;

            }
        });
        _freeCount++;
    }
}

void ThreadPool::SimplePool::shut() {
//    std::cout << "thread pool is shutting now" << std::endl;
    while (!_tasks.empty()) {
    }
}


